package top.lanscarlos.ashcraft.repository;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.sun.istack.NotNull;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Repository;
import top.lanscarlos.ashcraft.pojo.Cart;
import top.lanscarlos.ashcraft.pojo.CartItem;
import top.lanscarlos.ashcraft.pojo.User;

/**
 * Ashcraft
 * top.lanscarlos.ashcraft.repository
 *
 * @author Lanscarlos
 * @since 2022-05-26 17:55
 */
@Repository
public class CartRepository {
    @Autowired
    private SessionFactory sessionFactory;
    @Autowired
    private Gson gson;

    public Object query(@NotNull int userId) {
        Cart cart = null;
        Session session = sessionFactory.openSession();
        try {
            User user = session.get(User.class, userId);
            if (user == null) return null;
            return toJson(user.getCart());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return cart;
    }

    public boolean save(Cart cart, @Nullable CartItem cartItem) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            if (cartItem != null) {
                session.saveOrUpdate(cartItem);
            }
            session.saveOrUpdate(cart);
            transaction.commit();
            return true;
        } catch (Exception e) {
            if (transaction != null) transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return false;
    }

    public JsonElement toJsonTree(Object object) {
        return gson.toJsonTree(object);
    }

    public JsonElement toJson(Object object) {
        return toJsonTree(object);
    }
}
